import json
import logging
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from celery_task.build_index.tasks import build_index_one


class MyHandler(FileSystemEventHandler):
    def on_created(self, event):
        # 当新增文件时触发此方法
        logging.info(f'Watchdog: New file created[{event.src_path}]')
        build_index_one.delay(event.src_path)


if __name__ == "__main__":
    # 要监视的文件夹路径
    with open('./config.json', 'r') as f:
        folder_to_watch = json.loads(f.read()).get('monitor_path')

    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, folder_to_watch, recursive=True)
    observer.start()
    logging.info('Start Monitor')

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()
